package com.iemes.controller.work_scheduling;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.iemes.annotation.SystemLog;
import com.iemes.controller.index.BaseController;
import com.iemes.entity.FlowStepFormMap;
import com.iemes.entity.OperationFormMap;
import com.iemes.entity.ProcessWorkFlowFormMap;
import com.iemes.entity.SfcStepFormMap;
import com.iemes.entity.ShopOrderSfcFormMap;
import com.iemes.entity.ShoporderFormMap;
import com.iemes.entity.StepChangeHistoryFormMap;
import com.iemes.exception.BusinessException;
import com.iemes.mapper.base.BaseMapper;
import com.iemes.service.CommonService;
import com.iemes.service.WorkScheduling.WorkStepChangeService;
import com.iemes.util.Common;
import com.iemes.util.ListUtils;
import com.iemes.util.ResponseHelp;
import com.iemes.util.ShiroSecurityHelper;

/**
 * 
 */
@Controller
@RequestMapping("/work_scheduling/work_step_change/")
public class WorkStepChangeController extends BaseController {

	@Inject
	private BaseMapper baseMapper;

	@Inject
	private CommonService commonService;

	@Inject
	private WorkStepChangeService workStepChangeService;

	private Logger log = Logger.getLogger(this.getClass());
	private String workStepChangeUrl = Common.BACKGROUND_PATH + "/work_scheduling/work_step_change/work_step_change";

	// 页面跳转
	@RequestMapping("work_step_change")
	public String Get_work_step_change_Url(Model model) throws Exception {
		model.addAttribute("res", findByRes());
		setSfcStatusList(model);
		setSfcStepStatusList(model);
		return workStepChangeUrl;
	}

	private void setSfcStatusList(Model model) {
		Map<String, String> map = new HashMap<String, String>();
		int[] statusArray = new int[] { 0, 1, 2, 3, 4 };
		for (int status : statusArray) {
			map.put(String.valueOf(status), commonService.getSfcStatusStr(status));
		}
		model.addAttribute("sfcStatusList", map);
	}

	private void setSfcStepStatusList(Model model) {
		Map<String, String> map = new HashMap<String, String>();
		int[] statusArray = new int[] { 0, 1, 2, 3, 4 };
		for (int status : statusArray) {
			map.put(String.valueOf(status), commonService.getSfcStepStatusStr(status));
		}
		model.addAttribute("sfcStepStatusList", map);
	}

	/**
	 * 调整作业步骤
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("changeWorkStep")
	@SystemLog(module = "车间作业步骤调整", methods = "车间作业步骤调整-步骤调整") // 凡需要处理业务逻辑的.都需要记录操作日志
	public String changeWorkStep() {
		ShopOrderSfcFormMap shopOrderSfcFormMap = getFormMap(ShopOrderSfcFormMap.class);
		try {
			changeWorkStep(shopOrderSfcFormMap);
		} catch (BusinessException e) {
			log.error(e.getMessage());
			return ResponseHelp.responseErrorText(e.getMessage());
		}
		return ResponseHelp.responseText();
	}
	
	public void changeWorkStep(ShopOrderSfcFormMap shopOrderSfcFormMap) throws BusinessException {
		try {
			String sfcId = shopOrderSfcFormMap.getStr("id");

			// 1.添加或者更新工单的基本信息
			if (StringUtils.isEmpty(sfcId)) {
				throw new BusinessException("sfc ID为空，不允许步骤调整！请检索sfc！");
			} else {
				ShopOrderSfcFormMap shopOrderSfcFormMap2 = new ShopOrderSfcFormMap();
				shopOrderSfcFormMap2.put("id", sfcId);
				List<ShopOrderSfcFormMap> listShopOrderSfcFormMap = baseMapper.findByNames(shopOrderSfcFormMap2);
				if (!ListUtils.isNotNull(listShopOrderSfcFormMap)) {
					throw new BusinessException("无法找到sfc信息，不允许步骤调整！请与系统管理员联系！");
				}
				shopOrderSfcFormMap2 = listShopOrderSfcFormMap.get(0);
				int sfcStatus = shopOrderSfcFormMap2.getInt("sfc_status");
				if (sfcStatus != 0 && sfcStatus != 1) {
					throw new BusinessException("sfc处于" + commonService.getSfcStatusStr(sfcStatus) + "状态，不允许调整步骤！");
				}
				
				// 获取sfc的当前步骤
				String sfcCurrentOperationId = "";
				SfcStepFormMap sfcStepFormMap = new SfcStepFormMap();
				sfcStepFormMap.put("shoporder_sfc_id", sfcId);
				sfcStepFormMap.put("orderby", " order by seq desc ");
				List<SfcStepFormMap> listSfcStepFormMap = baseMapper.findByNames(sfcStepFormMap);
				if (ListUtils.isNotNull(listSfcStepFormMap)) {
					sfcStepFormMap = listSfcStepFormMap.get(0);
					sfcCurrentOperationId = sfcStepFormMap.getStr("operation_id");
				} else {
					throw new BusinessException("sfc步骤信息为空，不允许步骤调整！请与系统管理员联系！");
				}
				
				String sfcNewOperationId = shopOrderSfcFormMap.getStr("new_operation_id");
				if(StringUtils.isEmpty(sfcNewOperationId)) {
					throw new BusinessException("新的步骤为空，不允许步骤调整！");
				}
				if (sfcCurrentOperationId.equals(sfcNewOperationId)) {
					// 新旧状态一样，不需要做更改
					return;
				}
				
				int newOperationStatus = 0;
				if(sfcNewOperationId.equals("STEP_END")) {
					newOperationStatus = 2;
				}else {
					FlowStepFormMap flowStepFormMap = new FlowStepFormMap();
					flowStepFormMap.put("operation_id", sfcNewOperationId);
					List<FlowStepFormMap> listFlowStepFormMap = baseMapper.findByNames(flowStepFormMap);
					if (ListUtils.isNotNull(listFlowStepFormMap)) {
						//throw new BusinessException("sfc新步骤信息为空，不允许步骤调整！请与系统管理员联系！");
						flowStepFormMap = listFlowStepFormMap.get(0);
						newOperationStatus = flowStepFormMap.getInt("status");
					}
				}
				//获取工单
				ShoporderFormMap shoporderFormMap = new ShoporderFormMap();
				List<ShoporderFormMap> listShoporderFormMap = baseMapper.findByAttribute("id",
						sfcStepFormMap.getStr("shoporder_id"), ShoporderFormMap.class);
				if (listShoporderFormMap.size() > 0) {
					shoporderFormMap = listShoporderFormMap.get(0);
				} else {
					throw new BusinessException("sfc对应的工单信息为空，不允许步骤调整！请与系统管理员联系！");
				}
				
				
				//获取工艺路线信息
				String workflowId = shoporderFormMap.getStr("process_workflow_id");

				ProcessWorkFlowFormMap processWorkFlowFormMap = new ProcessWorkFlowFormMap();
				processWorkFlowFormMap.put("id", workflowId);
				List<ProcessWorkFlowFormMap> listProcessWorkFlowFormMap = baseMapper.findByNames(processWorkFlowFormMap);
				if (!ListUtils.isNotNull(listProcessWorkFlowFormMap)) {
					throw new BusinessException("未检索到工单的工艺路线信息，不允许步骤调整！请与系统管理员联系！");
				}
				int isAllowChangFlow = listProcessWorkFlowFormMap.get(0).getInt("allowpass");
				if(isAllowChangFlow == -1) {
					throw new BusinessException("工艺路线 "+ listProcessWorkFlowFormMap.get(0).getStr("process_workflow") +" 不允许步骤调整！请与系统管理员联系！");
			
				}
				
				//获取工单的所有sfc列表
				ShopOrderSfcFormMap shopOrderSfcFormMap3 = new ShopOrderSfcFormMap();
				StringBuffer where = new StringBuffer();
				where.append(" where 1=1 ");
				where.append(" and shoporder_id = '" + sfcStepFormMap.getStr("shoporder_id") + "' ");
				where.append(" and sfc_status in ('2','3')");
				shopOrderSfcFormMap3.put("where", where.toString());
				List<ShopOrderSfcFormMap> listShopOrderSfcFormMapOfOneShoporder = baseMapper.findByWhere(shopOrderSfcFormMap3);

				// 调整sfc的作业步骤
				workStepChangeService.changeWorkStep(sfcStepFormMap, shopOrderSfcFormMap,shopOrderSfcFormMap2,
						shoporderFormMap,listShopOrderSfcFormMapOfOneShoporder,newOperationStatus);
			}

		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new BusinessException("作业步骤调整失败！" + e.getMessage());
		}
	}

	/**
	 * 检索作业步骤信息
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("queryWorkStep")
	public String queryWorkStep(Model model, HttpServletRequest request) {
		String siteId = ShiroSecurityHelper.getSiteId();
		String sfcNo = request.getParameter("sfc_no");
		// 1.查询sfc的基本信息
		String sfcId = "";
		ShopOrderSfcFormMap shopOrderSfcFormMap = new ShopOrderSfcFormMap();
		shopOrderSfcFormMap.put("sfc", sfcNo);
		shopOrderSfcFormMap.put("site_id", siteId);
		List<ShopOrderSfcFormMap> listShopOrderSfcFormMap = baseMapper.findByNames(shopOrderSfcFormMap);
		if (!ListUtils.isNotNull(listShopOrderSfcFormMap)) {
			String errMessage = "未检索到sfc编号为：" + sfcNo.toUpperCase() + "的信息";
			log.error(errMessage);
			model.addAttribute("res", findByRes());
			setSfcStatusList(model);
			setSfcStepStatusList(model);
			model.addAttribute("errorMessage", errMessage);
			return workStepChangeUrl;
		}
		shopOrderSfcFormMap = listShopOrderSfcFormMap.get(0);
		sfcId = shopOrderSfcFormMap.getStr("id");

		// 2.查询sfc的当前作业信息
		querySfcStep(model, sfcId);

		// 3.查询sfc对应得工艺路线步骤列表信息
		String shoporderId = shopOrderSfcFormMap.getStr("shoporder_id");
		querySfcWorkflowStep(model, sfcId, shoporderId);

		// 4.查询sfc步骤调整的历史信息
		queryStepChangeHistory(model, sfcId);

		setSfcStatusList(model);
		setSfcStepStatusList(model);
		model.addAttribute("shopOrderSfcFormMap", shopOrderSfcFormMap);
		model.addAttribute("successMessage", "检索成功");
		return workStepChangeUrl;
	}

	public void querySfcStep(Model model, String sfcId) {
		SfcStepFormMap sfcStepFormMap = new SfcStepFormMap();
		sfcStepFormMap.put("shoporder_sfc_id", sfcId);
		sfcStepFormMap.put("orderby", " order by seq desc ");
		List<SfcStepFormMap> listSfcStepFormMap = baseMapper.findByNames(sfcStepFormMap);
		if (ListUtils.isNotNull(listSfcStepFormMap)) {
			// 获取sfc的当前步骤信息
			sfcStepFormMap = listSfcStepFormMap.get(0);
			setOperationStr(sfcStepFormMap);
			model.addAttribute("sfcStepFormMap", sfcStepFormMap);
		}
	}

	public void querySfcWorkflowStep(Model model, String sfcId, String shoporderId) {
		// 1.查询工单的基本信息
		ShoporderFormMap shoporderFormMap = new ShoporderFormMap();
		shoporderFormMap.put("id", shoporderId);
		List<ShoporderFormMap> listShoporderFormMap = baseMapper.findByNames(shoporderFormMap);
		if (!ListUtils.isNotNull(listShoporderFormMap)) {
			log.error("未检索到sfc的工单信息");
			model.addAttribute("errorMessage", "未检索到sfc的工单信息");
			return;
		}
		// 2.查工艺路线步驟
		shoporderFormMap = listShoporderFormMap.get(0);
		String workflowId = shoporderFormMap.getStr("process_workflow_id");

		FlowStepFormMap flowStepFormMap = new FlowStepFormMap();
		flowStepFormMap.put("process_workflow_id", workflowId);
		List<FlowStepFormMap> listFlowStepFormMap = baseMapper.findByNames(flowStepFormMap);
		if (!ListUtils.isNotNull(listFlowStepFormMap)) {
			log.error("未检索到工单的工艺路线信息");
			model.addAttribute("errorMessage", "未检索到工单的工艺路线信息");
			return;
		}
		//获取操作的名称
		for(FlowStepFormMap map : listFlowStepFormMap) {
			String operationId = map.getStr("operation_id");
			String NextOperationId = map.getStr("next_operation_id");
			
			map.put("operation", findOperationNameByOperationId(operationId));
			map.put("next_operation", findOperationNameByOperationId(NextOperationId));
		}
		// 对步骤进行排序
		sortSfcWorkflowStep(listFlowStepFormMap);
		model.addAttribute("flowStepFormMapList", listSortFlowStepFormMap);
		
		//取得新步骤列表
		List<FlowStepFormMap> listNewSortFlowStepFormMap = new ArrayList<FlowStepFormMap>();
		List<String> newStepList = new ArrayList<String>();
		for(int i=0;i<listSortFlowStepFormMap.size();i++) {
			FlowStepFormMap map = listSortFlowStepFormMap.get(i);
			String operationId = map.getStr("operation_id");
			String nextOperationId = map.getStr("next_operation_id");
			String operation = map.getStr("operation");
			String nextOperation = map.getStr("next_operation");
			
			if(!newStepList.contains(operationId)) {
				FlowStepFormMap newStepMap = new FlowStepFormMap();
				newStepMap.put("operation_id", operationId);
				newStepMap.put("operation", operation);
				listNewSortFlowStepFormMap.add(newStepMap);
				newStepList.add(operationId);
			}
			if(!newStepList.contains(nextOperationId)) {
				FlowStepFormMap newStepMap = new FlowStepFormMap();
				newStepMap.put("operation_id", nextOperationId);
				newStepMap.put("operation", nextOperation);
				listNewSortFlowStepFormMap.add(newStepMap);
				newStepList.add(nextOperationId);
			}
		}
		model.addAttribute("newflowStepFormMapList", listNewSortFlowStepFormMap);
	}
	private String findOperationNameByOperationId(String operationId) {
		String operationName = "";
		OperationFormMap operationFormMap = new OperationFormMap();
		operationFormMap.put("id", operationId);
		List<OperationFormMap> listOperationFormMap = baseMapper.findByNames(operationFormMap);
		if(ListUtils.isNotNull(listOperationFormMap)) {
			operationFormMap = listOperationFormMap.get(0);
			operationName = operationFormMap.getStr("operation_no");
		}
		return operationName;
	}

	List<FlowStepFormMap> listSortFlowStepFormMap = new ArrayList<FlowStepFormMap>();
	List<String> listTempOpearetionId = new ArrayList<String>();
	

	public void sortSfcWorkflowStep(List<FlowStepFormMap> listFlowStepFormMap) {
		listSortFlowStepFormMap.clear();
		listTempOpearetionId.clear();
		List<FlowStepFormMap> firstFlowStepFormMaps = getFirstStepFlowMaps(listFlowStepFormMap);
		List<String> firstNextopList = new ArrayList<>();
		for (int i = 0; i < firstFlowStepFormMaps.size(); i++) {
			FlowStepFormMap firstFlowStepFormMap = firstFlowStepFormMaps.get(i);
			if (!firstNextopList.contains(firstFlowStepFormMap.getStr("next_operation_id"))) {
				firstNextopList.add(firstFlowStepFormMap.getStr("next_operation_id"));
				List<FlowStepFormMap> childList = getChildList(listFlowStepFormMap, firstFlowStepFormMap);// 得到子节点列表
				listSortFlowStepFormMap.add(firstFlowStepFormMap);
				listTempOpearetionId.add(firstFlowStepFormMap.getStr("operation_id"));
				listTempOpearetionId.add(firstFlowStepFormMap.getStr("next_operation_id"));
				if (ListUtils.isNotNull(childList)) {
					recursionFn(listFlowStepFormMap, firstFlowStepFormMap, childList, true);
				}
			}
		}
	}

	public void recursionFn(List<FlowStepFormMap> list, FlowStepFormMap curr, List<FlowStepFormMap> childList,
			Boolean isRecursion) {
		if (ListUtils.isNotNull(childList)) {
			if (isRecursion) {
				for (FlowStepFormMap child : childList) {
					listSortFlowStepFormMap.add(child);
				}
				for (FlowStepFormMap child : childList) {
					List<FlowStepFormMap> childListComman = getChildList(list, child);
					String chlidNextOpId = child.getStr("next_operation_id");
					if (listTempOpearetionId.contains(chlidNextOpId)) {
						recursionFn(list, child, childListComman, false);
					} else {
						recursionFn(list, child, childListComman, true);
					}
					listTempOpearetionId.add(chlidNextOpId);
				}
			}
		}
	}

	private List<FlowStepFormMap> getFirstStepFlowMaps(List<FlowStepFormMap> listFlowStepFormMap) {
		List<FlowStepFormMap> maps = new ArrayList<>();
		for (FlowStepFormMap map : listFlowStepFormMap) {
			int status = map.getInt("status");
			if (status == 1) {
				maps.add(map);
			}
		}
		return maps;
	}

	private List<FlowStepFormMap> getChildList(List<FlowStepFormMap> list, FlowStepFormMap curr) {
		List<FlowStepFormMap> childList = new ArrayList<FlowStepFormMap>();
		String currOp = curr.getStr("next_operation_id");
		for (FlowStepFormMap map : list) {
			String op = map.getStr("operation_id");
			if (op.equals(currOp)) {
				childList.add(map);
			}
		}
		return childList;
	}

	public void queryStepChangeHistory(Model model, String sfcId) {
		StepChangeHistoryFormMap stepChangeHistoryFormMap = new StepChangeHistoryFormMap();
		stepChangeHistoryFormMap.put("sfc_id", sfcId);
		stepChangeHistoryFormMap.put("orderby", " order by create_time desc");
		List<StepChangeHistoryFormMap> listStepChangeHistoryFormMap = baseMapper.findByNames(stepChangeHistoryFormMap);
		if (ListUtils.isNotNull(listStepChangeHistoryFormMap)) {
			for (int i = 0; i < listStepChangeHistoryFormMap.size(); i++) {
				StepChangeHistoryFormMap map = listStepChangeHistoryFormMap.get(i);
				String stepIdBeforeChange = map.getStr("step_id_before_change");
				String stepIdAfterChange = map.getStr("step_id_after_change");

				SfcStepFormMap sfcStepFormMapBeforeChange = new SfcStepFormMap();
				sfcStepFormMapBeforeChange.put("id", stepIdBeforeChange);
				List<SfcStepFormMap> listSfcStepFormMap = baseMapper.findByNames(sfcStepFormMapBeforeChange);
				if (ListUtils.isNotNull(listSfcStepFormMap)) {
					// 获取sfc的当前步骤信息
					sfcStepFormMapBeforeChange = listSfcStepFormMap.get(0);
					setOperationStr(sfcStepFormMapBeforeChange);
					map.put("sfcStepFormMapBeforeChange", sfcStepFormMapBeforeChange);
				}
				SfcStepFormMap sfcStepFormMapAfterChange = new SfcStepFormMap();
				sfcStepFormMapAfterChange.put("id", stepIdAfterChange);
				List<SfcStepFormMap> listSfcStepFormMap2 = baseMapper.findByNames(sfcStepFormMapAfterChange);
				if (ListUtils.isNotNull(listSfcStepFormMap2)) {
					// 获取sfc的当前步骤信息
					sfcStepFormMapAfterChange = listSfcStepFormMap2.get(0);
					setOperationStr(sfcStepFormMapAfterChange);
					map.put("sfcStepFormMapAfterChange", sfcStepFormMapAfterChange);
				}

			}
			model.addAttribute("stepChangeHistory", listStepChangeHistoryFormMap);
		}
	}

	private void setOperationStr(SfcStepFormMap sfcStepFormMap) {
		String operationId = sfcStepFormMap.getStr("operation_id");
		String operationName = findOperationNameByOperationId(operationId);
		sfcStepFormMap.put("operation", operationName);
	}

}